import os
import signal
import time 
import libtmux

def killport(port):
    '''root authority is required'''
    try:
        command="kill -9 $(netstat -nlp | grep :"+str(port)+" | awk '{print $7}' | awk -F'/' '{{ print $1 }}')"
        os.system(command)
        print(f"killing {port} is succeed.")
    except:
        pass 
        print(f"{port} no need to kill")
    time.sleep(2)

if __name__ == "__main__":

    ports = [7860, 7861, 7862, 7863, 7864, 7865, 7866, 7867]
    print("正在kill进程")
    for p in ports:
        killport(p)

    command_to_serve = [
        f"python server.py --server_port 7860 --gpu_id 0",
        f"python server.py --server_port 7861 --gpu_id 1",
        f"python server.py --server_port 7862 --gpu_id 2",
        f"python server.py --server_port 7863 --gpu_id 3",
        f"python server.py --server_port 7864 --gpu_id 4",
        f"python server.py --server_port 7865 --gpu_id 5",
        f"python server.py --server_port 7866 --gpu_id 6",
        f"python server.py --server_port 7867 --gpu_id 7",
    ]

    server = libtmux.Server()
    print(server.list_sessions())

    all_sessions = []
    for s in server.list_sessions():
        all_sessions.append(str(s)[str(s).index(" ")+1:-1])
    
    print(all_sessions)

    # exit(0)
    index = 0
    for s_name in ports:
        if str(s_name) in all_sessions:
            s = server.find_where({"session_name": str(s_name)})
        else :
            s = server.new_session(str(s_name))

        print(f"正在启动程序：{s_name}")
        # s.attached_
        pane = s.attached_pane
        pane.send_keys(command_to_serve[index])
        pane.enter()
        time.sleep(1)
        index += 1

